<?php
declare(strict_types=1);

namespace Modules\Configuration\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Illuminate\Support\Facades\DB;
use Modules\Common\Support\Upload\Uploader;
use Modules\Configuration\Models\Configuration;
use Illuminate\Http\Request;
use Modules\LessonTime\Models\LessonTime;
use Modules\User\Models\User;


class ConfigurationController extends Controller
{
    public function __construct(
        protected readonly Configuration $model
    ){}

    /**
     * @return mixed
     */
    public function index(): mixed
    {
        $result = [];
        $config = Configuration::query()->first();
        $timeId = explode("," ,$config['time_ids']);
        $timeLs = LessonTime::query()->select()->get();

        foreach ($timeLs as $timeL)
        {
            $result['all_time'][] = [
                "id" => $timeL['id'],
                "name" => $timeL['start_time'] . "~" . $timeL['end_time'],
            ];
        }

        $result['choose_time'] = $this->transferInt($timeId);
        $result['max_rev_day'] = $config['max_rev_day'];
        $result['max_cancel_time'] = $config['max_cancel_time'];
        $result['about_us'] = $config['about_us'];
        $result['banners']  = explode(",", $config['banners']);

        return $result;
    }

    public function saveConfig(Request $request)
    {
        $data = [];
        $post = $request->all();
        if(isset($post['max_rev_day'])) $data['max_rev_day'] = $post['max_rev_day'];
        if(isset($post['max_cancel_time'])) $data['max_cancel_time'] = $post['max_cancel_time'];
        if(isset($post['about_us'])) $data['about_us'] = $post['about_us'];
        if(isset($post['banners'])) $data['banners'] = $post['banners'];
        if(isset($post['choose_time'])) $data['time_ids'] = $post['choose_time'];

        return $this->model->updateBy(1, $data);
    }

    public function defaultLessonTimes()
    {
        $config = Configuration::query()->first();
        $timeId = isset($config['time_ids']) ? explode("," ,$config['time_ids']) : [];

        $times = LessonTime::query()->select(['id',"start_time","end_time","time_long"])->whereIn("id",$timeId)->get();

        foreach ($times as &$time)
        {
            $time['time_str'] = $time['start_time'] . "~" . $time['end_time'];
        }

        return $times;
    }

    /**
     * 上传图片
     * @param Request $request
     * @param Uploader $uploader
     * @return array
     */
    public function image(Request $request, Uploader $uploader): array
    {
        return $uploader->upload($request->file('file'));
    }


    public function transferInt($strList = [])
    {
        $intList = [];
        foreach ($strList as $strVal)
        {
            $intList[] = (int) $strVal;
        }

        return $intList;
    }
}
